package ru.ognick.coachsystem.manager;

import java.io.File;
import java.util.ArrayList;

import ru.ognick.coachsystem.common.IOFile;
import ru.ognick.coachsystem.common.Training;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class TrainingAdapter extends ArrayAdapter<TrainingView> {
    public final String TAG = getClass().getSimpleName();	
	private ArrayList<TrainingView> trainings;
	public TrainingAdapter(Context context, 
							   int textViewResourceId, 
							   ArrayList<TrainingView> trainings) {
		super(context, textViewResourceId, trainings);
		this.trainings = trainings;
		setNotifyOnChange(true);
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		return trainings.get(position).getView();
	}
	
	public TrainingView getItem(int position) {
		return trainings.get(position);
	}
	
	public void remove(TrainingView trainingView){
		if (trainingView.getTraining().delete()) {
			trainings.remove(trainingView);
	        notifyDataSetChanged();
		}
		
	}
	
	public TrainingView add(Training training){
        Log.d(TAG, "SaveData " + trainings.size());
        final TrainingView trainingView = new TrainingView(getContext(), training); 
		trainings.add(trainingView);
        notifyDataSetChanged();
        return trainingView;
	}
	
	public void loadStored(OnClickListener l) {
		trainings.clear();
        for (File f : IOFile.getFiles()) {
        	Training training = Training.load(f);
        	TrainingView trainingView = add(training);
        	trainingView.getView().setOnClickListener(l);
        	Log.d(TAG, "LoadData " + training.getFilename().getName());
        }
        
        Log.d(TAG, "LoadData " + trainings.size());
        notifyDataSetChanged();
	}
	
	

}
